# -*- coding:utf-8 -*-
from django.contrib.admin.views.decorators import staff_member_required
from django.template.response import TemplateResponse
from django.contrib import messages
from django.contrib.admin import helpers
from callcentre.models import TMobileTyping
from manualpick.models import TWechatUser


@staff_member_required
def pick_list(request):

    if (request.method == 'POST' and
            'index' in request.POST and '_save' not in request.POST):
        selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
        if selected:
            response = _response_action(request, TMobileTyping.objects.filter(pk__in=selected))
            if response:
                return response
        else:
            message = 'Items must be selected in order to perform actions on them. No items have been changed.'
            messages.add_message(request, messages.WARNING, message, extra_tags='', fail_silently=False)

    qs = TMobileTyping.objects.raw('''
select id,mobile,name,sex,create_user,ctime 
from t_mobile_typing where status = 0 limit 5
''')
    cl = {'has_filters': False,
          'formset': {'is_multipart': False,
                      'errors': None},
          }
    qs_wechat = TWechatUser.objects.filter(create_user=request.user.username)

    actions = qs_wechat.filter(status=TWechatUser.ENABLED).values('username', 'nickname')

    context = {'results': qs,
               'actions': actions,
               'actions_on_top': True,
               'cl': cl,
               'messages': messages.get_messages(request)

               }

    return TemplateResponse(request, 'admin/manualpick/tmobilepick/pick_list.html', context)
    # return render(request, 'admin/manualpick/tmobilepick/pick_list.html')


def _response_action(request, queryset):
    from datetime import datetime
    from manualpick.models import TMobilePick

    def get_ip():
        """获取客户端的IP地址"""
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            return request.META['HTTP_X_FORWARDED_FOR']
        return request.META['REMOTE_ADDR']

    try:
        action_index = int(request.POST.get('index', 0))
    except ValueError:
        action_index = 0

    # Construct the action form.
    data = request.POST.copy()
    data.pop(helpers.ACTION_CHECKBOX_NAME, None)
    data.pop("index", None)

    # Use the action whose button was pushed
    try:
        data.update({'action': data.getlist('action')[action_index]})
    except IndexError:
        # If we didn't get an action from the chosen form that's invalid
        # POST data, so by deleting action it'll fail the validation check
        # below. So no need to do anything here
        pass

    if data['action'] == 'pick_selected' or data['action'] != '':
        wechat_username, wechat_nickname = data['action'].split('_', 1)
        for item in queryset:
            if item.status > 0:
                continue

            pick_obj = TMobilePick(mobile=item.mobile,
                                   wechat=wechat_nickname,
                                   note=wechat_username,
                                   create_user=request.user,
                                   client_ip=get_ip(),
                                   status=0,
                                   status_text="from %s at %s" % (item.create_user, datetime.now())
                                   )
            pick_obj.save()

            item.status = 1
            item.save()

        context = dict(
            model_count=queryset.count(),
            queryset=queryset,
            wechat=data['action'],
        )

        request.current_app = ''

        return TemplateResponse(request, 'admin/manualpick/tmobilepick/pick_list_results.html', context)
